import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.beans.Expression;
import java.io.IOException;

public class ExpressDomParse {
    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        Document document = null;
        try {
            document = builder.parse("d://cd.xml");
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获得根节点
        Element element = document.getDocumentElement();
        String tagName = element.getTagName();
        System.out.println(tagName);

        NodeList nodeList = document.getElementsByTagName("conpany");

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            String textContent = node.getTextContent();
            System.out.println(textContent);
        }


        //根据标签名获得值
        for (int j = 0; j < 2; j++) {
            Element rootElement = (Element) document.getElementsByTagName("song").item(j);
            NodeList nodeList1 = rootElement.getChildNodes();
            for (int i = 0; i < nodeList1.getLength(); i++) {
                Node node = nodeList1.item(i);
                if (node instanceof Element) {
                    Element ele = (Element) node;
                    if (ele.getTagName().equals("singerName")) {
                        String singerName = ele.getTextContent();
                        System.out.println("singerName:" + singerName);
                    }
                    if (ele.getTagName().equals("songName")) {
                        String songName = ele.getTextContent();
                        System.out.println("songName:" + songName);
                    }
                    if (ele.getTagName().equals("publishYear")) {
                        String publishYear = ele.getTextContent();
                        System.out.println("publishYear:" + publishYear);
                    }
                    if (ele.getTagName().equals("company")) {
                        String company = ele.getTextContent();
                        System.out.println("company:" + company);
                    }
                /*String textContent = node.getTextContent();
                System.out.println(textContent);*/
                }

            }
        }
    }
}
